<template>
    <div class="upload-container">
        <el-dialog :visible.sync="dialogVisible" append-to-body="true">
            <el-upload
                :multiple="true"
                :file-list="fileList"
                :show-file-list="true"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                :before-upload="beforeUpload"
                class="editor-slide-upload"
                action="https://httpbin.org/post"
                list-type="picture-card"
            >
                <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
            </el-upload>
            <el-button @click="dialogVisible = false" icon="el-icon-close">取 消</el-button>
            <el-button type="primary" @click="confirm" icon="el-icon-check">确 定</el-button>
            <span style="color:red;float: right;" v-if="!!pictureTip">{{ pictureTip }}</span>
        </el-dialog>
    </div>
</template>

<script>
// import { getToken } from 'api/qiniu'

export default {
    name: "UploadImg",
    data() {
        return {
            dialogVisible: false,
            listObj: {},
            fileList: []
        };
    },
    props: {
        type: {
            default: ["image/jpeg", "image/png", "image/jpg"],
            type: Array
        },
        size: {
            default: 1,
            type: Number
        },
        imgWidth: {
            default: 600,
            type: Number
        },
        imgHeight: {
            default: 0,
            type: Number
        },
        pictureTip: {
            type: String,
            default: ''
        },
    },
    methods: {
        checkAllSuccess() {
            return Object.keys(this.listObj).every(
                item => this.listObj[item].hasSuccess
            );
        },
        confirm() {
            const arr = Object.keys(this.listObj).map(v => this.listObj[v]);
            if (!this.checkAllSuccess()) {
                this.$message({
                    type: "warning",
                    message: `请等待所有图片上传成功 或 出现了网络问题，请刷新页面重新上传！`
                });
                return;
            }
            this.$emit("successCBK", arr);
        },
        handleSuccess(response, file) {
            const uid = file.uid;
            const objKeyArr = Object.keys(this.listObj);
            for (let i = 0, len = objKeyArr.length; i < len; i++) {
                if (this.listObj[objKeyArr[i]].uid === uid) {
                    this.listObj[objKeyArr[i]].url = response.files.file;
                    this.listObj[objKeyArr[i]].hasSuccess = true;
                    return;
                }
            }
        },
        handleRemove(file) {
            const uid = file.uid;
            const objKeyArr = Object.keys(this.listObj);
            for (let i = 0, len = objKeyArr.length; i < len; i++) {
                if (this.listObj[objKeyArr[i]].uid === uid) {
                    delete this.listObj[objKeyArr[i]];
                    return;
                }
            }
        },
        beforeUpload(file) {
            if (this.type.indexOf(file.type) == -1) {
                this.$message({
                    type: "warning",
                    message: `上传图片格式不正确，只支持${this.type.join(
                        ","
                    )}格式的图片上传`
                });
                return false;
            }
            if (parseFloat(this.size) < file.size / 1024 / 1024) {
                this.$message({
                    type: "warning",
                    message: `上传图片不能大于${this.size}M`
                });
                return false;
            }
            const _self = this;
            const _URL = window.URL || window.webkitURL;
            const fileName = file.uid;
            this.listObj[fileName] = {};
            return new Promise((resolve, reject) => {
                const img = new Image();
                img.src = _URL.createObjectURL(file);
                img.onload = function() {
                    let imgWidth = parseFloat(_self.imgWidth);
                    let imgHeight = parseFloat(_self.imgHeight);
                    _self.listObj[fileName] = {
                        hasSuccess: false,
                        uid: file.uid,
                        width: this.width > imgWidth ? imgWidth : this.width,
                        height:
                            this.width > imgWidth
                                ? (imgWidth / this.width) * this.height
                                : this.height
                    };
                    if (imgHeight > 0) {
                        _self.listObj[fileName].height = imgHeight;
                    }
                };
                resolve(true);
            });
        }
    },
    watch: {
        dialogVisible(val, oldVal) {
            if (!val) {
                this.listObj = {};
                this.fileList = [];
            }
        }
    }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.editor-slide-upload {
    margin-bottom: 20px;
    ::v-deep .el-upload--picture-card {
        width: 100%;
    }
}
</style>
